<template>
  <PageContainer
    title="车辆到站"
    description="确认到达本站的车辆，处理到货订单"
    :columns="columns"
    :data-source="dataSource"
    :loading="loading"
    :show-filters="true"
    :query-params="queryParams"
    :pagination-data="paginationData"
    :scroll="{ x: 1200, y: 'calc(100vh - 350px)' }"
    @search="handleSearch"
    @reset="handleReset"
    @pagination-change="handlePaginationChange"
  >
    <!-- 查询条件 -->
    <template #filter-items>
      <a-form-item label="车牌号/司机">
        <a-input
          v-model:value="queryParams.keyword"
          placeholder="输入车牌号或司机姓名"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="始发站">
        <a-input
          v-model:value="queryParams.departureSite"
          placeholder="输入始发站"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="发车日期">
        <a-range-picker
          v-model:value="queryParams.dispatchDateRange"
          :placeholder="['开始日期', '结束日期']"
          format="YYYY-MM-DD"
        />
      </a-form-item>
    </template>

    <!-- 表格内容 -->
    <template #bodyCell="{ column, record }">
      <!-- 车辆信息列 -->
      <template v-if="column.key === 'vehicleInfo'">
        <div class="vehicle-info">
          <div class="vehicle-main">
            <span class="vehicle-plate">{{ record.vehiclePlate }}</span>
          </div>
        </div>
      </template>

      <!-- 司机信息列 -->
      <template v-if="column.key === 'driverInfo'">
        <div class="driver-info">
          <div class="driver-name">{{ record.driverName || "-" }}</div>
          <div class="driver-phone">{{ record.driverPhone || "-" }}</div>
        </div>
      </template>

      <!-- 订单数量列 -->
      <template v-else-if="column.key === 'orderCount'">
        <span style="color: var(--primary-color); font-weight: 500">
          {{ record.orderCount || 0 }}
        </span>
      </template>

      <!-- 始发站列 -->
      <template v-else-if="column.key === 'departureSite'">
        <span>{{ record.departureSiteName || "-" }}</span>
      </template>

      <!-- 目的地列 -->
      <template v-else-if="column.key === 'arrivalSite'">
        {{ record.arrivalSiteName || record.destination }}
      </template>

      <!-- 发车时间列 -->
      <template v-else-if="column.key === 'dispatchTime'">
        <div v-if="record.actualDepartureTime">
          {{ formatDateTime(record.actualDepartureTime) }}
        </div>
        <span v-else style="color: #999">-</span>
      </template>

      <!-- 发车状态列 -->
      <template v-else-if="column.key === 'dispatchStatus'">
        <a-tag :color="getStatusColor(record.dispatchStatus)">
          {{ getStatusText(record.dispatchStatus) }}
        </a-tag>
      </template>

      <!-- 操作列 -->
      <template v-else-if="column.key === 'actions'">
        <a-space>
          <a-button
            v-if="record.dispatchStatus === 'DISPATCHED'"
            type="link"
            size="small"
            @click="showArrivalModal(record)"
          >
            确认到站
          </a-button>
          <a-button type="link" size="small" @click="viewOrders(record)">
            查看订单
          </a-button>
        </a-space>
      </template>
    </template>
  </PageContainer>

  <!-- 确认到站弹窗 -->
  <a-modal
    v-model:open="arrivalModalVisible"
    title="确认车辆到站"
    :confirm-loading="confirmLoading"
    @ok="handleConfirmArrival"
    @cancel="handleCancelArrival"
  >
    <a-form :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-form-item label="车牌号">
        <span>{{ currentRecord?.vehiclePlate }}</span>
      </a-form-item>
      <a-form-item label="司机">
        <span
          >{{ currentRecord?.driverName }}
          {{ currentRecord?.driverPhone }}</span
        >
      </a-form-item>
      <a-form-item label="始发站">
        <span>{{ currentRecord?.departureSiteName }}</span>
      </a-form-item>
      <a-form-item label="订单数量">
        <span style="color: var(--primary-color); font-weight: 500">{{
          currentRecord?.orderCount || 0
        }}</span>
      </a-form-item>
      <a-form-item label="实际到站时间">
        <a-date-picker
          v-model:value="arrivalForm.actualArrivalTime"
          show-time
          format="YYYY-MM-DD HH:mm:ss"
          placeholder="选择到站时间"
          style="width: 100%"
        />
      </a-form-item>
      <a-form-item label="备注">
        <a-textarea
          v-model:value="arrivalForm.remark"
          placeholder="输入备注信息（可选）"
          :rows="3"
        />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { message } from "ant-design-vue";
import PageContainer from "@/components/business/PageContainer.vue";
import dayjs, { Dayjs } from "dayjs";
import { useUserStore } from "@/stores/user";
import { useRouter } from "vue-router";

const userStore = useUserStore();
const router = useRouter();

// 数据状态
const loading = ref(false);
const dataSource = ref<any[]>([]);
const paginationData = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});

// 查询参数
const queryParams = reactive({
  keyword: "",
  departureSite: "",
  dispatchDateRange: undefined as [Dayjs, Dayjs] | undefined,
});

// 确认到站相关
const arrivalModalVisible = ref(false);
const confirmLoading = ref(false);
const currentRecord = ref<any>(null);
const arrivalForm = reactive({
  actualArrivalTime: dayjs() as Dayjs | null,
  remark: "",
});

// 表格列定义
const columns = [
  {
    title: "车辆信息",
    key: "vehicleInfo",
    width: 180,
  },
  {
    title: "司机信息",
    key: "driverInfo",
    width: 150,
  },
  {
    title: "始发站",
    key: "departureSite",
    dataIndex: "departureSiteName",
    width: 120,
  },
  {
    title: "目的地",
    key: "arrivalSite",
    dataIndex: "arrivalSiteName",
    width: 120,
  },
  {
    title: "订单数量",
    key: "orderCount",
    dataIndex: "orderCount",
    width: 100,
    align: "center" as const,
  },
  {
    title: "发车时间",
    key: "dispatchTime",
    width: 160,
  },
  {
    title: "发车状态",
    key: "dispatchStatus",
    width: 100,
  },
  {
    title: "操作",
    key: "actions",
    width: 180,
    align: "center" as const,
    fixed: "right" as const,
  },
];

// 获取数据
const fetchData = async () => {
  loading.value = true;
  try {
    const { getDispatchList } = await import("@/api/dispatch");

    const params: any = {
      current: paginationData.current,
      size: paginationData.pageSize,
      keyword: queryParams.keyword,
      departureSite: queryParams.departureSite,
      // 查询目的地是本站点的记录（包括在途和已到站）
      arrivalSiteId: userStore.currentSite?.id,
      statuses: ["DISPATCHED", "ARRIVED"], // 已发车和已到站
    };

    if (queryParams.dispatchDateRange) {
      params.dispatchStartDate =
        queryParams.dispatchDateRange[0].format("YYYY-MM-DD");
      params.dispatchEndDate =
        queryParams.dispatchDateRange[1].format("YYYY-MM-DD");
    }

    const response = await getDispatchList(params);
    dataSource.value = response.data.records || [];
    paginationData.total = response.data.total || 0;
  } catch (error: any) {
    message.error(error.message || "获取数据失败");
    console.error("Fetch data error:", error);
  } finally {
    loading.value = false;
  }
};

// 搜索
const handleSearch = () => {
  paginationData.current = 1;
  fetchData();
};

// 重置
const handleReset = () => {
  queryParams.keyword = "";
  queryParams.departureSite = "";
  queryParams.dispatchDateRange = undefined;
  paginationData.current = 1;
  fetchData();
};

// 分页变化
const handlePaginationChange = (page: number, pageSize: number) => {
  paginationData.current = page;
  paginationData.pageSize = pageSize;
  fetchData();
};

// 显示确认到站弹窗
const showArrivalModal = (record: any) => {
  currentRecord.value = record;
  arrivalForm.actualArrivalTime = dayjs();
  arrivalForm.remark = "";
  arrivalModalVisible.value = true;
};

// 确认到站
const handleConfirmArrival = async () => {
  if (!currentRecord.value) return;

  confirmLoading.value = true;
  try {
    const { confirmArrival } = await import("@/api/dispatch");

    await confirmArrival({
      dispatchId: currentRecord.value.id,
      actualArrivalTime: arrivalForm.actualArrivalTime?.format(
        "YYYY-MM-DDTHH:mm:ss"
      ),
      remark: arrivalForm.remark,
    });

    message.success("车辆到站确认成功");
    arrivalModalVisible.value = false;
    fetchData();
  } catch (error: any) {
    message.error(error.message || "确认到站失败");
    console.error("Confirm arrival error:", error);
  } finally {
    confirmLoading.value = false;
  }
};

// 取消到站
const handleCancelArrival = () => {
  arrivalModalVisible.value = false;
  currentRecord.value = null;
};

// 查看订单
const viewOrders = async (record: any) => {
  try {
    // 跳转到到货中心的车辆订单页面，传递完整的车辆和司机信息
    router.push({
      path: `/tenant/arrival/vehicle/${record.vehicleId}`,
      query: {
        vehiclePlate: record.vehiclePlate,
        driverName: record.driverName || "",
        driverPhone: record.driverPhone || "",
        driverId: record.driverId || "",
      },
    });
  } catch (error) {
    message.error("跳转车辆订单页面失败");
    console.error("Navigate to vehicle orders error:", error);
  }
};

// 获取状态颜色
const getStatusColor = (status: string) => {
  const statusColors: Record<string, string> = {
    READY: "warning",
    DISPATCHED: "processing",
    ARRIVED: "success",
    CANCELLED: "error",
  };
  return statusColors[status] || "default";
};

// 获取状态文本
const getStatusText = (status: string) => {
  const statusTexts: Record<string, string> = {
    READY: "待发车",
    DISPATCHED: "已发车",
    ARRIVED: "已到达",
    CANCELLED: "已取消",
  };
  return statusTexts[status] || status;
};

// 格式化日期时间
const formatDateTime = (datetime: string) => {
  return dayjs(datetime).format("YYYY-MM-DD HH:mm:ss");
};

// 初始化
onMounted(() => {
  fetchData();
});
</script>

<style scoped lang="scss">
.vehicle-info {
  .vehicle-main {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .vehicle-plate {
    font-weight: 500;
    color: var(--text-primary);
    letter-spacing: 0.5px;
  }
}

.driver-info {
  .driver-name {
    font-weight: 500;
    color: var(--text-primary);
  }

  .driver-phone {
    font-size: 12px;
    color: var(--text-secondary);
  }
}

/* 操作按钮样式优化 */
:deep(.ant-space-item) {
  .ant-btn-sm {
    display: flex;
    align-items: center;
    gap: 4px;

    .anticon {
      font-size: 12px;
    }
  }

  .ant-btn-primary {
    background-color: var(--primary-color);
    border-color: var(--primary-color);

    &:hover {
      background-color: var(--primary-hover);
      border-color: var(--primary-hover);
    }
  }
}
</style>
